R markdown creates interactive reports from R code. This post provides a few tips to improve the appearance of output documents. In any case, the bible is the Rstudio documentation.

1 Text formating


R markdown allows to easily format your text. You can add links, write in bold or italic. This is very well explained in the Rstudio cheatsheet.

Here is the code I used to make this paragraph:

R markdown allows to easily format your text. You can add [links](www.r-graph-gallery.com), write in **bold** or *italic*. This is very well explained in the [Rstudio cheatsheet](https://www.rstudio.com/wp-content/uploads/2015/02/rmarkdown-cheatsheet.pdf).

2 Horizontal lines


Add an horizontal line by adding 3 stars:

***

3 Chapter auto numbering


Header of level 1, 2, 3 are set using #, ## and ###. You can auto number your chapters using this option the header:

---
title: "Your title"
output: 
  html_document:
    number_sections: TRUE
---

# Title
## A subtitle
## Another subtitle

# Another title

4 Skip a line


I really like to add spaces in my document to give it a more uncluttered look. This is done using the <br> command. This .rmd code:

A first sentence
<br><br><br><br>
A seconde sentence

will give this htmloutput


A first sentence



A seconde sentence


5 Center an image


To center an image, use this code:

<center>
![FigName](logo_r_graph_gallery.jpg)
</center>
Here is the result
FigName

7 Add space before title


I find it pleasant to have a bit of space before starting a new chapter. You can use a <br> before each header. A more convenient way is to add some margin in your CSS. Create a style.css file:

h1, .h1, h2, .h2, h3, .h3 {
    margin-top: 84px;
}

A rmd document that takes into account this .css file:

---
title: "A document with a CSS included"
output:
  html_document:
    css: style.css
---

A title will follow, but with a lot of space before it

# Title 1

content of part 1

# Title 2

content of part 2

The document you are reading uses this css. See the separation between chapters.

8 Add caption to your figures


Specify the caption of your figure in the chunk header. Example:

{r, fig.align="center", fig.width=6, fig.height=6, fig.cap="Figure: Here is a really important caption."}
library(tidyverse)
mpg %>%
  ggplot( aes(x=reorder(class, hwy), y=hwy, fill=class)) + 
    geom_boxplot() +
    xlab("class") +
    theme(legend.position="none")
Figure: Here is a really important caption.

Figure: Here is a really important caption.

9 Custom caption


Change the black default caption using CSS. Adding this code in your style.css file.

<style>
p.caption {
  font-size: 0.9em;
  font-style: italic;
  color: grey;
  margin-right: 10%;
  margin-left: 10%;  
  text-align: justify;
}
</style>
file will give this result:
Figure: Here is a really important caption, customized to be grey and in italic.

Figure: Here is a really important caption, customized to be grey and in italic.

10 Use buttons for sub-chapters


Save space in your document using buttons for sub chapters. Add this code at the end of your title:

# Use pills {.tabset .tabset-fade .tabset-pills}

Your subtitles will appear like that:

10.1 First

Note that I’ve custom the buttons using this CSS:

.btn {
    border-width: 0 0px 0px 0px;
    font-weight: normal;
    text-transform: ;
}
.btn-default {
    color: #2ecc71;
    background-color: #ffffff;
    border-color: #ffffff;
}

10.2 Second

content of sub-chapter #2

10.3 Third

content of sub-chapter #3

11 Use DT for tables


The DT library is my favourite option to display tables in your document. It allows to:

library(DT)
datatable(mtcars, rownames = FALSE, filter="top", options = list(pageLength = 5, scrollX=T) )

12 Hide code


If you share your code with somebody who’s more focus on results than code, or if your code chunks are very long, you probably want to hide the code, but still allow the reader to consult it if necessary. This is possible by modifying the YAML header of your document:

output:
  html_document:
    code_folding: "hide"

13 Highlight a piece of text


You can apply some css to a specific part of your document. Here is an example where I change the background color of a small part. Handy to highlight conclusions at the end of your document.

Code:

<style>
div.blue { background-color:#e6f0ff; border-radius: 5px; padding: 20px;}
</style>
<div class = "blue">

- This is my first conclusion
- This is my second conclusion

</div>
Will give:
  • This is my first conclusion
  • This is my second conclusion

14 Cache code

Possible to cache code. But better to use it with care. Personnaly use it at the end, just to make the document pretty.

16 Use interactive graphics.


R allows to build any type of interactive graphic. My favourite library is plotly that will turn any of your ggplot2 graphic interactive in one supplementary line of code. Try to hover points, to select a zone, to click on the legend.

library(ggplot2)
library(plotly)
library(gapminder)
 
p <- gapminder %>%
  filter(year==1977) %>%
  ggplot( aes(gdpPercap, lifeExp, size = pop, color=continent)) +
  geom_point() +
  scale_x_log10() +
  theme_bw()
 
ggplotly(p)

17 Use a template


Customize the document appearance using one of the existing template:

18 Share it online


Display your html online using github. Follow these steps:

See more detailed instructions here.

19 Compile several in a website


Explanation in the R Markdown Websites section of the R Markdown website. To run a basic example:

library(rmarkdown)
rmarkdown::render_site()

20 Create template


If you often use the same kind of customization you probably want to create your own .rmd template. A good starting point is the Rstudio documentation.

This document is produced using my personal template: epuRate. An easy solution to create your template can be to fork / download this repo and apply your own style instead of mine.

21 Add a session info


It is a good practice to add a session info at the end of your document. It will increase reproducibility and costs only one line of code

sessionInfo()
## R version 3.4.1 (2017-06-30)
## Platform: x86_64-apple-darwin15.6.0 (64-bit)
## Running under: macOS Sierra 10.12.6
## 
## Matrix products: default
## BLAS: /Library/Frameworks/R.framework/Versions/3.4/Resources/lib/libRblas.0.dylib
## LAPACK: /Library/Frameworks/R.framework/Versions/3.4/Resources/lib/libRlapack.dylib
## 
## locale:
## [1] en_AU.UTF-8/en_AU.UTF-8/en_AU.UTF-8/C/en_AU.UTF-8/en_AU.UTF-8
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
##  [1] bindrcpp_0.2    gapminder_0.3.0 plotly_4.7.1    DT_0.2         
##  [5] forcats_0.2.0   stringr_1.2.0   dplyr_0.7.4     purrr_0.2.4    
##  [9] readr_1.1.1     tidyr_0.7.2     tibble_1.4.2    ggplot2_2.2.1  
## [13] tidyverse_1.2.1 rmarkdown_1.8   epuRate_0.1    
## 
## loaded via a namespace (and not attached):
##  [1] reshape2_1.4.3      haven_1.1.0         lattice_0.20-35    
##  [4] colorspace_1.3-2    viridisLite_0.2.0   htmltools_0.3.6    
##  [7] yaml_2.1.16         rlang_0.1.6.9003    pillar_1.1.0       
## [10] foreign_0.8-69      glue_1.2.0          modelr_0.1.1       
## [13] readxl_1.0.0        bindr_0.1           plyr_1.8.4         
## [16] munsell_0.4.3       gtable_0.2.0        cellranger_1.1.0   
## [19] rvest_0.3.2         htmlwidgets_1.1     psych_1.7.8        
## [22] evaluate_0.10.1     labeling_0.3        knitr_1.18.7       
## [25] httpuv_1.3.5        crosstalk_1.0.0     parallel_3.4.1     
## [28] highr_0.6           broom_0.4.2         Rcpp_0.12.14       
## [31] xtable_1.8-2        scales_0.5.0.9000   backports_1.1.1    
## [34] jsonlite_1.5        mime_0.5            mnormt_1.5-5       
## [37] hms_0.3             digest_0.6.14       stringi_1.1.5      
## [40] shiny_1.0.5         grid_3.4.1          rprojroot_1.2      
## [43] cli_1.0.0           tools_3.4.1         magrittr_1.5       
## [46] lazyeval_0.2.1      crayon_1.3.4        pkgconfig_2.0.1    
## [49] data.table_1.10.4-3 xml2_1.1.1          lubridate_1.7.1    
## [52] assertthat_0.2.0    httr_1.3.1          rstudioapi_0.7     
## [55] R6_2.2.2            nlme_3.1-131        compiler_3.4.1

22 References


 

A work by Yan Holtz

Yan.holtz.data@gmail.com